package offer.easy;

import java.util.Arrays;

public class Mutiply {

    public static int[] resultArray(int[] array) {
        int temp = 0;
        int[] result = new int[array.length];

        for (int i = 0; i < array.length; i++) {
            temp = array[i];
            array[i] = 1;
            result[i] = 1;
            for (int j = 0; j < array.length; j++) {
                result[i] = result[i] * array[j];
            }
            array[i] = temp;
        }
        return result;
    }

    public static int[] resultArray2(int[] array) {
        int[] pre = new int[array.length];
        int[] tail = new int[array.length];
        int[] result = new int[array.length];

        pre[0] = 1;
        tail[tail.length-1] = 1;

        for (int i = 1; i < pre.length; i++) {
            pre[i] = pre[i-1] * array[i-1];
        }

        for (int i = tail.length - 2; i >= 0; i--) {
            tail[i] = tail[i+1] * array[i+1];
        }

        for (int i = 0; i < result.length; i++) {
            result[i] = pre[i] * tail[i];
        }
        return result;
    }

    public static void main(String[] args) {
        int[] array = {1,2,3,4,5};
        int[] result = resultArray(array);
        System.out.println(Arrays.toString(array));
        System.out.println(Arrays.toString(result));

        result = resultArray2(array);
        System.out.println(Arrays.toString(array));
        System.out.println(Arrays.toString(result));
    }
}
